package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.web.dao.Store;

public class StoreService {
	
	public boolean findExistsByUsername(String username){
		return Store.me().findFirst("SELECT * FROM t_dict_store WHERE username=?",username)!=null;
	}
	
	/**
	 * 分页查找
	 */
	public Page<Record> findByPage(int pageNum, int pageSize, String title, int type, int attribute, int province, int city, int area){
		StringBuffer sBuffer = new StringBuffer(" FROM t_dict_store T WHERE 1=1");
		List<Object> params = new ArrayList<Object>();
		if(StrKit.notBlank(title)){
			sBuffer.append(" AND T.title LIKE ?");
			params.add("%"+title+"%");
		}
		if(type!=0){
			sBuffer.append(" AND T.type=?");
			params.add(type);
		}
		if(attribute!=0){
			sBuffer.append(" AND T.attribute=?");
			params.add(attribute);
		}
		if(area!=0){
			sBuffer.append(" AND T.province=? AND T.city=? AND T.area=?");
			params.add(province);params.add(city);params.add(area);
		}else if(city!=0){
			sBuffer.append(" AND T.province=? AND T.city=?");
			params.add(province);params.add(city);
		}else if(province!=0){
			sBuffer.append(" AND T.province=?");
			params.add(province);
		}
		sBuffer.append(" ORDER BY T.createDate DESC");
		return Db.paginate(pageNum, pageSize, "SELECT T.id,T.title,T.type,T.attribute,T.address,T.username,T.tel,T.thumb", sBuffer.toString(), params.toArray());
	}
	public List<Record> find(int province, int city, int area,String title){
		StringBuffer sBuffer = new StringBuffer("select id,title FROM t_dict_store T WHERE 1=1");
		List<Object> params = new ArrayList<Object>();
		if(StrKit.notBlank(title)){
			sBuffer.append(" AND T.title LIKE ?");
			params.add("%"+title+"%");
		}
		if(area!=0){
			sBuffer.append(" AND T.province=? AND T.city=? AND T.area=?");
			params.add(province);params.add(city);params.add(area);
		}else if(city!=0){
			sBuffer.append(" AND T.province=? AND T.city=?");
			params.add(province);params.add(city);
		}else if(province!=0){
			sBuffer.append(" AND T.province=?");
			params.add(province);
		}
		sBuffer.append(" ORDER BY T.createDate DESC");
		return Db.find(sBuffer.toString(),params.toArray());
	}
	
	public boolean addStore(Store newObject){
		return newObject.save();
	}
	
	public boolean delStore(int id){
		return Store.me().deleteById(id);
	}
	
	public boolean editStore(Store object){
		return object.update();
	}

	public Store findById(int id){
		return Store.me().findFirst("SELECT * FROM t_dict_store WHERE id=?",id);
	}
	
}
